//
//  CouponDetailSheet.swift
//  CMB250716
//
//  Created by Trae AI on 2025/01/11.
//

import SwiftUI

@available(iOS 16.0, *)
struct CouponDetailSheet: View {
    let coupon: Coupon
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    @State private var showingLoginAlert = false
    @State private var showingUnlockAlert = false
    @State private var unlockAlertMessage = ""
    @State private var unlockAlertTitle = ""
    @State private var navigateToMenu = false

    
    var body: some View {
        ZStack {
            // 背景渐变 - 使用新的配置化颜色系统
            LinearGradient(
                colors: CouponTheme.getGradientColors(for: coupon.title),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .overlay(
                // 添加光泽效果增强3D感
                LinearGradient(
                    colors: [
                        Color.white.opacity(0.2),
                        Color.clear,
                        Color.black.opacity(0.1)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .ignoresSafeArea()
            
            VStack(spacing: 0) {
                // 顶部返回按钮区域
                HStack {
                    Button(action: {
                        dismiss()
                    }) {
                        Image(systemName: "chevron.left")
                            .font(.title2)
                            .fontWeight(.semibold)
                            .foregroundColor(.white)
                            .frame(width: 32, height: 32)
                            .background(
                                Circle()
                                    .fill(Color.black.opacity(0.3))
                                    .overlay(
                                        Circle()
                                            .stroke(Color.white.opacity(0.2), lineWidth: 1)
                                    )
                            )
                            .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 1)
                    }
                    .buttonStyle(PlainButtonStyle())
                    
                    Spacer()
                }
                .padding(.horizontal, 20)
                .padding(.top, 16)
                
                // 拖拽指示器
                RoundedRectangle(cornerRadius: 2.5)
                    .fill(Color.white.opacity(0.3))
                    .frame(width: 40, height: 5)
                    .padding(.top, 12)
                    .padding(.bottom, 20)
                
                ScrollView {
                    VStack(alignment: .leading, spacing: 0.8) {
                        // 1. 礼券名字
                        HStack {
                            VStack(alignment: .leading, spacing: 0.8) {
                                Text(dataManager.currentLanguage == "zh" ? "礼券名字" : "Coupon Title")
                                    .font(.caption2)
                                    .foregroundColor(.white.opacity(0.8))
                                    .textCase(.uppercase)
                                    .kerning(0.5)
                                
                                Text(coupon.formattedTitle(language: dataManager.currentLanguage))
                                    .font(.headline)
                                    .fontWeight(.bold)
                                    .foregroundColor(.white)
                                    .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                            }
                            
                            Spacer()
                            
                            Button(action: {
                                handleUseNowTap()
                            }) {
                                Text(dataManager.currentLanguage == "zh" ? "立即使用" : "Use Now")
                                    .font(.caption)
                                    .fontWeight(.bold)
                                    .foregroundColor(getUseButtonTextColor())
                                    .padding(.horizontal, 16)
                                    .padding(.vertical, 8)
                                    .background(
                                        ZStack {
                                            // 3D立体效果背景
                                            Capsule()
                                                .fill(
                                                    LinearGradient(
                                                        gradient: Gradient(colors: [
                                                            getUseButtonBackgroundColor().opacity(1.0),
                                                            getUseButtonBackgroundColor().opacity(0.8)
                                                        ]),
                                                        startPoint: .top,
                                                        endPoint: .bottom
                                                    )
                                                )
                                                .shadow(color: .black.opacity(0.4), radius: 4, x: 0, y: 3)
                                                .shadow(color: .white.opacity(0.3), radius: 1, x: 0, y: -1)
                                            
                                            // 内部高光效果
                                            Capsule()
                                                .stroke(
                                                    LinearGradient(
                                                        gradient: Gradient(colors: [
                                                            Color.white.opacity(0.4),
                                                            Color.clear
                                                        ]),
                                                        startPoint: .top,
                                                        endPoint: .bottom
                                                    ),
                                                    lineWidth: 1
                                                )
                                        }
                                    )
                                    .scaleEffect(1.0)
                                    .animation(.easeInOut(duration: 0.1), value: false)
                            }
                            .buttonStyle(PlainButtonStyle())
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 2. 优惠
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "优惠" : "Discount")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatDiscountValue())
                                .font(.title2)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                                .frame(maxWidth: .infinity, alignment: .leading)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 3. 解锁条件
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "解锁条件" : "TO UNLOCK")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatUnlockConditions())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 4. 使用条件
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "使用条件" : "APPLIED CONDITIONS")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatCondition())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 5. 备注
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "备注" : "Remarks")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatRemarks())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 6. 有效期
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "有效期" : "Validity")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatValidityPeriod())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 6. 适用范围
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "适用范围" : "Applicable Items")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatApplicableItems())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                                .lineLimit(nil)
                                .fixedSize(horizontal: false, vertical: true)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 7. 适用时间
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "适用时间" : "Applicable Time")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatApplicableTime())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 8. 使用频率
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "使用频率" : "Usage Limit")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(formatUsageFrequency())
                                .font(.callout)
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        
                        // 免责声明
                        VStack(alignment: .leading, spacing: 0.8) {
                            Text(dataManager.currentLanguage == "zh" ? "免责声明" : "Disclaimer")
                                .font(.caption2)
                                .foregroundColor(.white.opacity(0.8))
                                .textCase(.uppercase)
                                .kerning(0.5)
                            
                            Text(dataManager.currentLanguage == "zh" ? 
                                 "礼券不可叠加使用。Cu Mr Bull 保留所有解释权。如因系统升级或业务调整需更改优惠内容，恕不另行通知，已购礼券不受影响，可在有效期内继续使用。" :
                                 "Coupons cannot be combined. Cu Mr Bull reserves all rights of interpretation. If changes to promotional content are needed due to system upgrades or business adjustments, no separate notice will be given. Purchased coupons are not affected and can continue to be used within the validity period.")
                                .font(.caption)
                                .foregroundColor(.white.opacity(0.7))
                                .lineLimit(nil)
                                .fixedSize(horizontal: false, vertical: true)
                                .shadow(color: .black.opacity(0.3), radius: 1, x: 0, y: 1)
                        }
                        .padding(.horizontal, 16)
                        .padding(.vertical, 6)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color.black.opacity(0.2))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                                )
                        )
                        .padding(.top, 6)
                    }
                    .padding(.horizontal, 24)
                    .padding(.bottom, 40)
                }
            }
        }
        .presentationDetents([.fraction(0.55)])
        .alert(dataManager.currentLanguage == "zh" ? "请登录" : "Please Login", isPresented: $showingLoginAlert) {
            Button(dataManager.currentLanguage == "zh" ? "确定" : "OK") {
                showingLoginAlert = false
            }
        } message: {
            Text(dataManager.currentLanguage == "zh" ? "请登录或免费注册会员，享受会员专属服务。" : "Please login or register for free to enjoy exclusive member services.")
        }
        .alert(unlockAlertTitle, isPresented: $showingUnlockAlert) {
            Button(dataManager.currentLanguage == "zh" ? "确定" : "OK") {
                showingUnlockAlert = false
            }
        } message: {
            Text(unlockAlertMessage)
        }
        .fullScreenCover(isPresented: $navigateToMenu) {
            NavigationView {
                MenuView()
                    .environmentObject(dataManager)
                    .onAppear {
                        // 自动选择当前优惠券到购物车的优惠券选择界面
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            dataManager.preSelectedCoupon = coupon
                        }
                    }
            }
        }
    }
    
    // MARK: - 处理 Use Now 按钮点击
    private func handleUseNowTap() {
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: dataManager.currentUser,
            dataManager: dataManager
        )
        
        switch unlockCondition {
        case .none:
            // 无限制，可直接使用 - 导航到菜单页面
            performMenuNavigation()
            
        case .loginRequired:
            // 需要登录
            showLoginRequiredAlert()
            
        case .membershipLevel(_):
            // 需要特定会员等级
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "会员等级不足" : "Membership Level Required",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .memberInfoComplete:
            // 需要完善会员信息
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "完善会员信息" : "Complete Member Info",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .activationConditions(let conditions):
            // 需要满足激活条件
            showActivationRequiredAlert(conditions: conditions)
            
        case .timeSlotRestricted:
            // 时间段限制
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "时间限制" : "Time Restriction",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .usageLimitReached:
            // 使用次数已达上限
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "使用次数已达上限" : "Usage Limit Reached",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .birthdayMonthRequired:
            // 需要在生日月份使用
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "生日月份限制" : "Birthday Month Required",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .usageFrequencyReached:
            // 使用频率已达上限
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "使用频率限制" : "Usage Frequency Limit",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .expired:
            // 优惠券已过期
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "优惠券已过期" : "Coupon Expired",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
            
        case .inactive:
            // 优惠券不可用
            showUnlockRequiredAlert(
                title: dataManager.currentLanguage == "zh" ? "优惠券不可用" : "Coupon Unavailable",
                message: CouponConfig.UnlockConditions.getUnlockMessage(for: unlockCondition, language: dataManager.currentLanguage)
            )
        }
    }
    
    // MARK: - 私有辅助方法
    
    /// 显示登录要求提示
    private func showLoginRequiredAlert() {
        showingLoginAlert = true
    }
    
    /// 显示解锁要求提示
    private func showUnlockRequiredAlert(title: String, message: String) {
        unlockAlertTitle = title
        unlockAlertMessage = message
        showingUnlockAlert = true
    }
    
    /// 显示激活条件要求提示
    private func showActivationRequiredAlert(conditions: String) {
        let title = dataManager.currentLanguage == "zh" ? "激活条件" : "Activation Required"
        showUnlockRequiredAlert(title: title, message: conditions)
    }
    
    /// 导航到菜单页面
    private func performMenuNavigation() {
        dismiss()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            // 通过通知中心发送跳转到菜单的消息
            NotificationCenter.default.post(
                name: NSNotification.Name("NavigateToMenu"),
                object: nil
            )
        }
    }
    
    // MARK: - Helper Functions
    
    private func formatDiscountValue() -> String {
        // 特殊处理免费优惠券
        if coupon.discountValue == 0 {
            if dataManager.currentLanguage == "zh" {
                return "免费"
            } else {
                return "Free"
            }
        }
        
        switch coupon.discountType {
        case .percentage:
            return "\(Int(coupon.discountValue))%"
        case .fixedAmount:
            return "S$\(String(format: "%.0f", coupon.discountValue))"
        }
    }
    
    private func formatDiscountType() -> String {
        if dataManager.currentLanguage == "zh" {
            return coupon.discountType.rawValue
        } else {
            return coupon.discountType.englishName
        }
    }
    
    private func getUseButtonBackgroundColor() -> Color {
        return CouponTheme.getButtonBackgroundColor(for: coupon.title)
    }
    
    private func getUseButtonTextColor() -> Color {
        return CouponTheme.getButtonTextColor(for: coupon.title)
    }
    
    // 格式化描述信息
    private func formatDescription() -> String {
        if dataManager.currentLanguage == "zh" {
            return coupon.description
        } else {
            // 英文描述映射 - 根据用户提供的表格数据更新
            switch coupon.title {
            case "新会员立减福利":
                return "S$5 off first order"
            case "新会员折扣":
                return "S$5 off first order"
            case "Calf会员福利":
                return "20% off sitewide"
            case "超值礼券配套":
                return "15 value coupons worth S$350"
            case "会员周末专享":
                return "50% off sitewide"
            case "会员 HighBall专享":
                return "Free HighBall or Whiskey (U.P. S$10/glass)"
            case "小牛欢迎咖啡":
                return "Free coffee (one cup per week)"
            case "小牛「神秘礼品」":
                return "Free gift"
            case "资料完善专属福利":
                return "S$5 off sitewide"
            case "生日月份专属福利":
                return "30% off sitewide"
            default:
                return coupon.description
            }
        }
    }
    
    private func formatUnlockConditions() -> String {
        if dataManager.currentLanguage == "zh" {
            return coupon.activationConditions ?? "无特殊要求"
        } else {
            return coupon.englishActivationConditions ?? "No special requirements"
        }
    }
    
    private func formatCondition() -> String {
        if dataManager.currentLanguage == "zh" {
            return "最低消费 S$\(Int(coupon.minimumSpend))"
        } else {
            return "Min. spend S$\(Int(coupon.minimumSpend))"
        }
    }
    
    private func formatRemarks() -> String {
        if dataManager.currentLanguage == "zh" {
            switch coupon.title {
            case "新会员立减福利":
                return "首单立减 S$5"
            case "超值礼券配套":
                return "全场 15% 折扣"
            case "会员周末专享":
                return "50% 全场折扣"
            case "会员 HighBall专享":
                return "HighBall 或 Whiskey 免费 （原价 S$10/杯）"
            case "小牛欢迎咖啡":
                return "免费咖啡（每周一杯）"
            case "小牛「神秘礼品」":
                return "免费礼品"
            case "资料完善专属福利":
                return "全场立减 S$5"
            case "生日月份专属福利":
                return "全场 30% 折扣"
            default:
                return "优惠详情"
            }
        } else {
            switch coupon.title {
            case "新会员立减福利":
                return "S$5 off first order"
            case "超值礼券配套":
                return "15% off sitewide"
            case "会员周末专享":
                return "50% off sitewide"
            case "会员 HighBall专享":
                return "Free HighBall or Whiskey (U.P. S$10/glass)"
            case "小牛欢迎咖啡":
                return "Free coffee (one cup per week)"
            case "小牛「神秘礼品」":
                return "Free gift （sitewide）"
            case "资料完善专属福利":
                return "S$5 off sitewide"
            case "生日月份专属福利":
                return "30% off sitewide"
            default:
                return "Discount details"
            }
        }
    }
    
    private func formatValidityPeriod() -> String {
        // 首先检查是否为长期有效优惠券（2070年以后的日期视为长期有效）
        let calendar = Calendar.current
        let year = calendar.component(.year, from: coupon.validUntil)
        
        if year >= 2070 {
            // 长期有效优惠券显示"N/A (长期有效)"
            return dataManager.currentLanguage == "zh" ? "N/A (长期有效)" : "N/A (Long-term valid)"
        }
        
        if let relativeDuration = coupon.relativeDuration {
            if dataManager.currentLanguage == "zh" {
                switch relativeDuration {
                case .days(30):
                    // Check if this is the new member discount
                    if coupon.title == "新会员立减福利" || coupon.title == "新会员折扣" {
                        return "注册后 30 天内"
                    } else {
                        return "30 天有效期"
                    }
                case .years(1):
                    return "购买之日起一年"
                default:
                    return formatDate(coupon.validUntil)
                }
            } else {
                switch relativeDuration {
                case .days(30):
                    // Check if this is the new member discount
                    if coupon.title == "新会员立减福利" || coupon.title == "新会员折扣" {
                        return "Within 30 days of registration"
                    } else {
                        return "No expiration"
                    }
                case .years(1):
                    return "Valid for 1 year from purchase"
                default:
                    return formatDate(coupon.validUntil)
                }
            }
        } else {
            // 长期有效的情况
            if dataManager.currentLanguage == "zh" {
                return "长期有效，无固定有效期"
            } else {
                return "No expiration"
            }
        }
    }
    
    private func formatApplicableItems() -> String {
        // 根据优惠券标题判断特殊情况
        if coupon.title == "会员 HighBall专享" || coupon.title == "HighBall Member Exclusive" {
            if dataManager.currentLanguage == "zh" {
                return "只限HighBall 和 Whiskey"
            } else {
                return "Only for HighBall and Whiskey"
            }
        }
        
        // 特殊处理神秘礼品 - 根据用户表格，适用范围应该是包括酒水的
        if coupon.title == "小牛「神秘礼品」" {
            if dataManager.currentLanguage == "zh" {
                return "所有菜品（包括酒水）"
            } else {
                return "All food items (including Alcohol and Drinks)"
            }
        }
        
        // 根据excludeAlcoholicBeverages属性判断
        if coupon.excludeAlcoholicBeverages {
            if dataManager.currentLanguage == "zh" {
                return "所有菜品（酒水除外）"
            } else {
                return "All food items (excluding Alcohol and Drinks)"
            }
        } else {
            if dataManager.currentLanguage == "zh" {
                return "所有菜品（包括酒水）"
            } else {
                return "All food items (including Alcohol and Drinks)"
            }
        }
    }
    
    private func formatApplicableTime() -> String {
        guard let timeSlots = coupon.applicableTimeSlots, !timeSlots.isEmpty else {
            // 如果没有时间限制，返回全时段
            if dataManager.currentLanguage == "zh" {
                return "全时段（周一至周五， 11 am 至 7 pm，周六 & 周日（11 am至 8 pm)）"
            } else {
                return "All day (Mon–Fri 11am–7pm, Sat & Sun 11am–8pm)"
            }
        }
        
        let timeSlot = timeSlots[0] // 假设只有一个时间段
        
        // 检查是否是周末专享（只有周六周日）
        if timeSlot.weekdays.sorted() == [1, 7] { // 周日=1, 周六=7
            if dataManager.currentLanguage == "zh" {
                return "周六 & 周日（11 am至8 pm)"
            } else {
                return "Sat & Sun (11am–8pm)"
            }
        }
        
        // 默认全时段
        if dataManager.currentLanguage == "zh" {
            return "全时段（周一至周五， 11 am 至 7 pm，周六 & 周日（11 am至 8 pm)）"
        } else {
            return "All day (Mon–Fri 11am–7pm, Sat & Sun 11am–8pm)"
        }
    }
    
    private func formatWeekdays(_ weekdays: [Int]) -> String {
        if weekdays.count == 7 {
            return dataManager.currentLanguage == "zh" ? "每天" : "Every day"
        }
        
        let weekdayNames = dataManager.currentLanguage == "zh" ?
            ["周日", "周一", "周二", "周三", "周四", "周五", "周六"] :
            ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
        
        let sortedWeekdays = weekdays.sorted()
        let names = sortedWeekdays.map { weekdayNames[$0 - 1] }
        
        if dataManager.currentLanguage == "zh" {
            return names.joined(separator: "、")
        } else {
            return names.joined(separator: ", ")
        }
    }
    
    private func formatUsageFrequency() -> String {
        guard let frequency = coupon.usageFrequency else {
            return dataManager.currentLanguage == "zh" ? "无限制" : "Once per account per day"
        }
        
        if dataManager.currentLanguage == "zh" {
            switch frequency {
            case .once:
                return "每人限用一次"
            case .daily:
                return "每人每日限用一次"
            case .weekly:
                return "每人每周限用一次"
            case .monthly:
                return "每人每月限用一次"
            case .yearly:
                return "每人每年限用一次"
            case .perOrder:
                return "每单限用一次"
            }
        } else {
            switch frequency {
            case .once:
                return "One-time use per person"
            case .daily:
                return "Once per person per day"
            case .weekly:
                return "Once per person per week"
            case .monthly:
                return "Once per person per month"
            case .yearly:
                return "Once per person per year"
            case .perOrder:
                return "One-time use per Order"
            }
        }
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        
        if dataManager.currentLanguage == "zh" {
            formatter.locale = Locale(identifier: "zh_CN")
        } else {
            formatter.locale = Locale(identifier: "en_US")
        }
        
        return formatter.string(from: date)
    }
}

#Preview {
    if #available(iOS 16.0, *) {
        CouponDetailSheet(coupon: Coupon(
        code: "WELCOME20",
        title: "新用户专享",
        englishTitle: "New User Exclusive",
        description: "新用户首次消费享受20%折扣",
        englishDescription: "New users enjoy 20% discount on first purchase",
        discountType: Coupon.DiscountType.percentage,
        discountValue: 20,
        minimumSpend: 50,
        maximumDiscount: 30,
        validFrom: Date(),
        validUntil: Calendar.current.date(byAdding: .month, value: 1, to: Date()) ?? Date(),
        isActive: true,
        usageLimit: nil as Int?,
        usageCount: 0,
        excludeAlcoholicBeverages: true,
        applicableTimeSlots: [
            TimeSlot(weekdays: [2, 3, 4, 5, 6], startTime: 660, endTime: 1140)
        ],
        usageFrequency: UsageFrequency.once,
        relativeDuration: nil as RelativeDuration?,
        reminderDays: 3,
        activationConditions: nil as String?,
        englishActivationConditions: nil as String?,
        requiresLogin: true,
        requiresMembershipLevel: nil as String?
        ))
        .environmentObject(DataManager.shared)
    } else {
        Text("Preview not available")
    }
}